package com.likou.top100;

import java.util.ArrayList;
import java.util.HashMap;

public class Demo002_两数相加 {
    public static void main(String[] args) {
        ListNode a = new ListNode();
        a.val = 1;
        ListNode b = new ListNode();
        b.val = 3;
        ListNode c = new ListNode();
        c.val = 7;
        a.next = b;
        b.next = c;
        ListNode listNode = addTwoNumbers(a, b);
        System.out.println();
    }
    public static ListNode addTwoNumbers3(ListNode l1, ListNode l2) {

        ListNode root = new ListNode(-1),pre = root;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {


            int l1Val = l1 != null ? l1.val : 0;
            int l2Val = l2 != null ? l2.val : 0;
            int sumVal = l1Val + l2Val + carry;
            carry = sumVal / 10;

            pre.next = new ListNode(sumVal % 10);
            pre = pre.next;

            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }

        return root.next;
    }
    /**
     * 维护变量进位t
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(-1), pre = dummyHead;
        int t = 0;
        //往下加计算的条件
        while (l1 != null || l2 != null || t != 0) {
            if (l1 != null) {
                t += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                t += l2.val;
                l2 = l2.next;
            }
            pre.next = new ListNode(t % 10);
            pre = pre.next;
            t /= 10;
        }

        return dummyHead.next;
    }

    /**
         *
         * @param l1
         * @param l2
         * @return
         */
        public static ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
            ListNode root = new ListNode(0);
            ListNode cursor = root;
            int carry = 0;
            while (l1 != null || l2 != null || carry != 0) {
                int l1Val = l1 != null ? l1.val : 0;
                int l2Val = l2 != null ? l2.val : 0;
                int sumVal = l1Val + l2Val + carry;
                carry = sumVal / 10;

                ListNode sumNode = new ListNode(sumVal % 10);
                cursor.next = sumNode;
                cursor = sumNode;

                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }

            return root.next;
    }
}


class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
